package xuegao.study.mall.rbac.controller;

import cn.hutool.core.collection.CollUtil;
import org.springframework.web.bind.annotation.*;
import xuegao.study.mall.common.model.ums.UmsAdmin;
import xuegao.study.mall.common.model.ums.UmsMember;
import xuegao.study.mall.common.model.ums.UmsMemberLevel;
import xuegao.study.mall.common.model.ums.UmsRole;
import xuegao.study.mall.rbac.common.CommonConstant;
import xuegao.study.mall.repo.dao.ums.UmsAdminDao;
import xuegao.study.mall.repo.dao.ums.UmsMemberDao;
import xuegao.study.mall.repo.dao.ums.UmsMemberLevelDao;
import xuegao.study.mall.repo.dao.ums.UmsRoleDao;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 对外开放接口(/open/api) 内部feign
 */
@RestController
@RequestMapping(CommonConstant.OPEN_API_PREFIX)
public class OpenRbacController {

    @Resource
    private UmsAdminDao umsAdminDao;

    @Resource
    private UmsRoleDao umsRoleDao;

    @Resource
    private UmsMemberDao umsMemberDao;

    @Resource
    private UmsMemberLevelDao umsMemberLevelDao;

    @GetMapping("/loadUserByUserName")
    public UmsAdmin loadUserByUserName(@RequestParam String username) {
        return umsAdminDao.getAdminByUsername(username);
    }

    @GetMapping("/getRoleByUserId")
    public List<String> getRoleByUserId(@RequestParam Long userId) {
        List<UmsRole> umsRoles = umsRoleDao.selectByAdminId(userId);
        List<String> roleNames = new ArrayList<>();
        if (CollUtil.isNotEmpty(umsRoles)) {
            roleNames = umsRoles.stream().map(UmsRole::getName).collect(Collectors.toList());
        }
        return roleNames;
    }

    @GetMapping("/loadUmsMemberByUserName")
    public UmsMember loadUmsMemberByUserName(@RequestParam String username) {
        Map<String, Object> params = new HashMap<>();
        params.put("username", username);
        return umsMemberDao.selectByMap(params).get(0);
    }

    @PostMapping("/registerUmsMember")
    public void registerUmsMember(@RequestBody UmsMember umsMember) {
        umsMemberDao.insert(umsMember);
    }

    @GetMapping("/loadDefaultUmsMemberLevel")
    public UmsMemberLevel loadDefaultUmsMemberLevel() {
        Map<String, Object> params = new HashMap<>();
        params.put("default_status", 1);
        return umsMemberLevelDao.selectByMap(params).get(0);
    }










}
